package com.example.orchid.paper.task;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.example.orchid.paper.http.HttpClientUtils;
import com.example.orchid.paper.util.FileUtils;
import com.example.orchid.paper.util.Logger;
import com.example.orchid.paper.util.SDCardUtils;
import com.example.orchid.paper.util.StreamUtils;
import com.example.orchid.paper.util.ZhihuUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 新闻详情页，WebView中图片列表下载Task
 * Created by Orchid on 2015-10-13.
 */
public class DetailImageDownloadTask extends BaseGetContentTask {

    public DetailImageDownloadTask(Context context, ResponseListener listener) {
        super(context, listener);
    }

    @Override
    protected String doInBackground(String... params) {
        String externalCacheDir = SDCardUtils.getExternalCacheDir(mContext);
        Log.i("paper externalCacheDir",externalCacheDir);
        if (params.length == 0 || TextUtils.isEmpty(externalCacheDir)) {
            return null;
        }

        File file;
        for (String param : params) {

            if (TextUtils.isEmpty(param)) {
                Logger.getLogger().e("no download, the image url is empty");
                continue;
            }

            String filePath = ZhihuUtils.getCacheImgFilePath(mContext, param);
            file = new File(filePath);

            boolean needDownload = true;

            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                long fileSize = FileUtils.getFileSize(filePath);

                if (fileSize == 0) {
                    // need re download
                } else {
                    needDownload = false;
                }
            }


            if (needDownload) {
                InputStream in = null;
                OutputStream out = null;

                //form web
                try {
                    in = HttpClientUtils.getStream(mContext, param, null);
                    Log.i("paper file", filePath);
                    out = new FileOutputStream(file);

                    StreamUtils.copy(in, out);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    StreamUtils.close(out);
                    StreamUtils.close(in);
                }
            } else {
                // no need download
            }
            publishProgress(param);

        }
        return null;
    }
}
